package com.gpj.learn.rocketmq.batch;

import com.gpj.learn.rocketmq.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @className SimpleBatchProducer
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/4/26 21:59
 * @version 1.0
 **/
@Slf4j
public class SimpleBatchProducer {
	public static void main(String[] args) {
		DefaultMQProducer producer = new DefaultMQProducer("BatchMessageProducerGroup");
		producer.setNamesrvAddr(CommonConstants.ROCKETMQ_NAMESERVER_ADDR);
		try {
			producer.start();
			List<Message> list = new ArrayList<>();
			for (int i = 0; i < 10; i++) {
				list.add(SimpleBatchProducer.createMessage());
			}
			producer.send(list); // 最大不超过4M
			log.info("{}条消息已发送", list.size());
		} catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
			e.printStackTrace();
		}finally {
			producer.shutdown();
		}
	}

	private static Message createMessage(){
		return new Message(CommonConstants.DEFAULT_TOPIC_NAME,
				"TagA", "key-" + UUID.randomUUID().toString(),
				"this is a batch message".getBytes(StandardCharsets.UTF_8));

	}
}
